package handlers

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"text-hub/models"
)

func Add(c *gin.Context) {
	img := c.PostForm("img")
	title := c.PostForm("title")
	content := c.PostForm("content")

	if img == "" || title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.Text{
		Img:     img,
		Title:   title,
		Content: content,
	}
	err := models.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "发布成功",
		})
	}
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var text []models.Text
	models.DB.Offset(offset).Limit(size).Find(&text).Debug()

	var total int64
	models.DB.Model(&models.Text{}).Count(&total).Debug()
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "success",
		"total": total,
	})
}
